package myJs


import scala.scalajs.js
import scala.scalajs.js.annotation.{JSExport, JSExportTopLevel}
import Utils._
import myPkg._
import myJs.myPkg.jquery._

import scala.collection.immutable.SeqMap
import scala.scalajs.js.Dynamic.{global => g}
import myJs.Implicits._
import myJs.myPkg.plotly.{Plotly, PlotlyConfigOptions}
import org.scalajs.dom
import org.scalajs.dom.document
import scalatags.Text.all._
import shared.plotly._
import shared.plotly.element.Color.StringColor
import shared.plotly.element._
import shared.plotly.layout.HoverMode.Closest
import shared.plotly.layout._

import scala.scalajs.js.JSConverters._
import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent.duration.DurationInt
import scala.util.{Failure, Success}

/**
 * Created by yz on 2019/4/15
 */
@JSExportTopLevel("PredictResult")
object PredictResult {

  var idStr: String = _

  @JSExport("init")
  def init = {
    //    showResult("368")
    dateInit
    registerEvent
  }

  def dateInit = {
    val options = DatepickerOptions.format("yyyy-mm-dd").autoclose(true).forceParse(true).language("zh-CN")
    $(".myDatepicker").datepicker(options)
  }

  def registerEvent = {
    $(document.body).on("change", s"#form .myDatepicker", "", (y: dom.Element) => {
      val startDate = Tool.getInputByName("startDate").myVal
      val endDate = Tool.getInputByName("endDate").myVal
      linearPlot(idStr, startDate, endDate)
    })
  }

  def linearPlot(id: String, startDate: String = "", endDate: String = "") = {
    val url = g.jsRoutes.controllers.PredictController.getLinearPlotData().url.toString
    MyFetch.get(url = s"${url}?missionId=${id}&startDate=${startDate}&endDate=${endDate}",
      headers = Map("Content-Type" -> "application/json")).map{any=>
      val rs = any.toJDJAn
      val array = rs("array").toJArJDJAn
      val dTick = rs.myGet("dTick")
      val colors = rs("colors").toJArS.map { x =>
        new StringColor(x)
      }.toList
      array.zipWithIndex.foreach { case (dict, i) =>
        val trace = Scatter(
          x = dict("x").toJArS.toList,
          y = dict("y").toJArS.toList,
          marker = Marker(
            color = colors
          )
        )
        val plotData = List(trace)
        val tickFormat = "%Y/%m/%d"
        val layout = if (i != 0) {
          Layout(
            xaxis = Axis(
              tickformat = tickFormat,
              dtick = dTick,
              fixedrange = true,
              tickangle = -45,
            ),
            hovermode = Closest,
            yaxis = Axis(
              fixedrange = true,
              title = dict.myGet("yTitle"),
            ),
            title = dict.myGet("title"),
            margin = Margin(b = 90, l = 70, t = 70, r = 10),
          )
        } else {
          Layout(
            xaxis = Axis(
              tickformat = tickFormat,
              dtick = dTick,
              fixedrange = true,
              tickangle = -45,
            ),
            hovermode = Closest,
            yaxis = Axis(
              fixedrange = true,
              title = dict.myGet("yTitle"),
              dtick = rs.myGet("ageDTick")
            ),
            title = dict.myGet("title"),
            margin = Margin(b = 90, l = 70, t = 70, r = 10),
          )
        }
        val config = PlotlyConfigOptions.displayModeBar(false)
        val gd = Plotly.newPlot(s"svg${i}", plotData, layout, config)
        val base64Trace = Scatter(
          x = dict("x").toJArS.toList,
          y = dict("y").toJArS.toList,
          marker = Marker(
            color = colors,
            size = 15
          )
        )
        val base64PlotData = List(base64Trace)
        val gridWidth = 3
        val base64Layout = if (i != 0) {
          Layout(
            xaxis = Axis(
              tickformat = tickFormat,
              dtick = dTick,
              fixedrange = true,
              tickangle = -45,
              tickfont = Font(
                size = 25
              ),
              gridwidth = gridWidth
            ),
            hovermode = Closest,
            yaxis = Axis(
              fixedrange = true,
              title = dict.myGet("yTitle"),
              tickfont = Font(
                size = 25
              ),
              titlefont = Font(
                size = 30
              ),
              gridwidth = gridWidth,
            ),
            title = dict.myGet("title"),
            margin = Margin(b = 150, l = 110, t = 70, r = 10),
            width = 800 * 2,
            height = 600 * 2,
            font = Font(
              size = 25
            )
          )
        } else {
          Layout(
            xaxis = Axis(
              tickformat = tickFormat,
              dtick = dTick,
              fixedrange = true,
              tickangle = -45,
              tickfont = Font(
                size = 25
              ),
              gridwidth = gridWidth
            ),
            hovermode = Closest,
            yaxis = Axis(
              fixedrange = true,
              title = dict.myGet("yTitle"),
              tickfont = Font(
                size = 25
              ),
              titlefont = Font(
                size = 30
              ),
              gridwidth = gridWidth,
              dtick = rs.myGet("ageDTick")
            ),
            title = dict.myGet("title"),
            margin = Margin(b = 150, l = 110, t = 70, r = 10),
            width = 800 * 2,
            height = 600 * 2,
            font = Font(
              size = 25
            )
          )
        }
        Plotly.toImage(base64PlotData, base64Layout).foreach { x =>
          Tool.getInputByName(s"base64${i}").`val`(x)
          //          $("#imgTest").attr("src", x)
        }
      }
    }.timeoutDeal

  }

  @JSExport("showResult")
  def showResult(id: String) = {
    $("#result").hide()
    $("#mode2,#mode3").hide()
    val index = layer.load(1, layerOptions.shade(js.Array("0.1", "#fff")))
    val url = g.jsRoutes.controllers.PredictController.predictResult().url.toString
    MyFetch.get(url = s"${url}?missionId=${id}",
      headers = Map("Content-Type" -> "application/json")).map { data =>
      val rs = data.asInstanceOf[js.Dictionary[js.Any]]
      layer.close(index)
      $("#showSampleId").text(rs.myGet("sampleId"))
      $("#showName").text(rs.myGet("name"))
      g.missionJson = rs("mission")
      g.extraDataJson = rs("extraData")
      idStr = id
      linearPlot(id)
      $("#result").show()
      var target_top = $("#result").offset().top
      $("html,body").animate(js.Dictionary("scrollTop" -> target_top), JQueryAnimationSettings.duration(800))
    }.timeoutDeal(index)
  }

}
